package org.batatasframework.rawdata;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.batatasframework.common.ParameterReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.bonoon.entities.AbstractRawdataImportItem;
import cn.bonoon.kernel.support.IOperator;
import cn.bonoon.kernel.util.StringHelper;

public abstract class AbstractRawdataParser<T extends AbstractRawdataImportItem> implements RawdataParser{
	protected RawdataDefinition definition;

	protected final Logger log = LoggerFactory.getLogger(this.getClass());
	
	@Override
	public List<? extends AbstractRawdataImportItem> parseWorkbook(
			Workbook workbook, 
			EntityManager entityManager, 
			ParameterReader parameter,
			IOperator operator) throws Exception{
		
		List<T> rowItems = new ArrayList<>(1000);
		//1.对上传的文件进行解析
		parseSheet(workbook.getSheetAt(0), rowItems);		
	
		//2.解析完成后，再进行各种判断、转换和处理
		return parse(rowItems, entityManager, parameter, operator);
	}
	
	AbstractRawdataParser<T> init(RawdataDefinition definition){
		this.definition = definition;
		return this;
	}
	
	protected List<T> parse(List<T> rowItems, EntityManager entityManager, ParameterReader parameter, IOperator operator){
		return rowItems;
	}
	
	protected String readOption(ParameterReader parameter){
		return parameter.getString(RawdataHandler.IMPORT_KEY + "_" + definition.getKey());
	}
	
	protected abstract T createItem();

	private void parseSheet(Sheet sheet, List<T> rowItems){
		int rowIndex = 0;
		
		for(Row row : sheet){
			rowIndex++;
			if(rowIndex > definition.startRow){
				T rowItem = createItem();
//				rowItem.setStatus(RawdataImportItemStatus.UNTREATED);
				
				if(parseRow(row, rowItem)){
					if (StringHelper.isNotEmpty(rowItem.getRemark())) {
						String remark=rowItem.getRemark();
						rowItem.setRemark(remark.substring(0,remark.length()-1));
					}
					rowItems.add(rowItem);
					//System.out.println("解析成功:"+rowIndex);
				}else{
					//解析不正确的行
					log.warn("解析不成功：" + rowIndex);
				}
				
				//if(!rowItem.error()){
				//}else{
				//	log.error("写入失败：" + rowIndex);
				//}
			}
		}
	}
	
	protected abstract boolean parseRow(Row row, T rowItem);
	
}
